package me.zhengjie.modules.workorder.service.impl;

import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.common.domain.TEngineerMoney;
import me.zhengjie.modules.common.service.TEngineerMoneyService;
import me.zhengjie.modules.customer.domain.TCustomerContract;
import me.zhengjie.modules.customer.service.TCustomerContractService;
import me.zhengjie.modules.serviceprovider.domain.TServiceproviderContract;
import me.zhengjie.modules.serviceprovider.domain.TServiceproviderPerson;
import me.zhengjie.modules.serviceprovider.service.TServiceproviderContractService;
import me.zhengjie.modules.serviceprovider.service.TServiceproviderPersonService;
import me.zhengjie.modules.serviceprovider.service.dto.TServiceproviderPersonDTO;
import me.zhengjie.modules.system.common.EnumWorkorderStatus;
import me.zhengjie.modules.workorder.domain.TCustomerSuggest;
import me.zhengjie.modules.workorder.domain.TWorkOrder;
import me.zhengjie.modules.workorder.domain.TWorkOrderLog;
import me.zhengjie.modules.workorder.repository.TWorkOrderRepository;
import me.zhengjie.modules.workorder.service.TWorkOrderLogService;
import me.zhengjie.utils.*;
import me.zhengjie.modules.workorder.repository.TCustomerSuggestRepository;
import me.zhengjie.modules.workorder.service.TCustomerSuggestService;
import me.zhengjie.modules.workorder.service.dto.TCustomerSuggestDTO;
import me.zhengjie.modules.workorder.service.dto.TCustomerSuggestQueryCriteria;
import me.zhengjie.modules.workorder.service.mapper.TCustomerSuggestMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.Date;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

/**
* @author zcw
* @date 2019-11-10
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class TCustomerSuggestServiceImpl implements TCustomerSuggestService {

    @Autowired
    private TCustomerSuggestRepository tCustomerSuggestRepository;

    @Autowired
    private TCustomerSuggestMapper tCustomerSuggestMapper;

    @Autowired
    private TWorkOrderRepository tWorkOrderRepository;

    @Autowired
    private TWorkOrderLogService tWorkOrderLogService;

    @Autowired
    private TServiceproviderContractService tServiceproviderContractService;

    @Autowired
    private TServiceproviderPersonService tServiceproviderPersonService;

    @Autowired
    private TEngineerMoneyService tEngineerMoneyService;

    @Autowired
    private TCustomerContractService tCustomerContractService;

    @Override
    public Object queryAll(TCustomerSuggestQueryCriteria criteria, Pageable pageable){
        Page<TCustomerSuggest> page = tCustomerSuggestRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(tCustomerSuggestMapper::toDto));
    }

    @Override
    public Object queryAll(TCustomerSuggestQueryCriteria criteria){
        return tCustomerSuggestMapper.toDto(tCustomerSuggestRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    public TCustomerSuggestDTO findById(Integer id) {
        Optional<TCustomerSuggest> tCustomerSuggest = tCustomerSuggestRepository.findById(id);
        ValidationUtil.isNull(tCustomerSuggest,"TCustomerSuggest","id",id);
        return tCustomerSuggestMapper.toDto(tCustomerSuggest.get());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TCustomerSuggestDTO create(TCustomerSuggest resources) {
        return tCustomerSuggestMapper.toDto(tCustomerSuggestRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(TCustomerSuggest resources) {
        Optional<TCustomerSuggest> optionalTCustomerSuggest = tCustomerSuggestRepository.findById(resources.getId());
        ValidationUtil.isNull( optionalTCustomerSuggest,"TCustomerSuggest","id",resources.getId());

        TCustomerSuggest tCustomerSuggest = optionalTCustomerSuggest.get();
        // 此处需自己修改
        tCustomerSuggest.setPresent(resources.getPresent());
        tCustomerSuggest.setPresentTime(resources.getPresentTime());
        tCustomerSuggest.setRevisitor(resources.getRevisitor());
        tCustomerSuggest.setRevisitorTime(resources.getRevisitorTime());
        tCustomerSuggestRepository.save(tCustomerSuggest);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Integer id) {
        tCustomerSuggestRepository.deleteById(id);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void evaluate(TCustomerSuggest resources) {
        TCustomerSuggest tCustomerSuggest = null ;
        if(resources.getId() != null) {
            Optional<TCustomerSuggest> optionalTCustomerSuggest = tCustomerSuggestRepository.findByOrderCode(resources.getOrderCode());
            if(optionalTCustomerSuggest.isPresent())
                tCustomerSuggest = optionalTCustomerSuggest.get();
        }

        if(tCustomerSuggest != null) {
            // 此处需自己修改
            tCustomerSuggest.setOrderCode(resources.getOrderCode());
            tCustomerSuggest.setSatisfaction(resources.getSatisfaction());
            tCustomerSuggest.setServiceTime(resources.getServiceTime());
            tCustomerSuggest.setContent(resources.getContent());
            tCustomerSuggest.setSuggest(resources.getSuggest());
            tCustomerSuggest.setEvaluator(resources.getEvaluator());
            tCustomerSuggest.setEvaluatorTime(resources.getEvaluatorTime());
            tCustomerSuggestRepository.save(tCustomerSuggest);
        } else {
            //新增
            tCustomerSuggest = new TCustomerSuggest();
            tCustomerSuggest.setPresent(0);
            tCustomerSuggest.setPresentTime(new Timestamp(System.currentTimeMillis()));
            tCustomerSuggest.setOrderCode(resources.getOrderCode());
            tCustomerSuggest.setSatisfaction(resources.getSatisfaction());
            tCustomerSuggest.setServiceTime(resources.getServiceTime());
            tCustomerSuggest.setContent(resources.getContent());
            tCustomerSuggest.setSuggest(resources.getSuggest());
            tCustomerSuggest.setEvaluator(resources.getEvaluator());
            tCustomerSuggest.setEvaluatorTime(resources.getEvaluatorTime());
            tCustomerSuggestRepository.save(tCustomerSuggest);
        }

        TWorkOrder order = tWorkOrderRepository.findFirstByOrderCode(resources.getOrderCode());
        if(order != null) {
            Long supplierId = order.getSupplier() ;  //供应商
            Optional<TServiceproviderContract> optional = tServiceproviderContractService.findLastEffectContract(21L, supplierId, DateUtil.parseDateToStr(new Date(), "yyyy-MM-dd"));

            if(!optional.isPresent()) {
                throw new BadRequestException(HttpStatus.BAD_REQUEST, "服务商未签订有效合同");
            }
            TServiceproviderContract contract = optional.get();

            /*
            TServiceproviderPersonDTO personDTO = tServiceproviderPersonService.findById(order.getSupplier());
            if(personDTO == null) {
                throw new BadRequestException(HttpStatus.BAD_REQUEST, "服务商为空");
            }*/

            //获取费用
            Long cost = tEngineerMoneyService.getEngineerConst(contract, order.getMajor(), order.getLevel());
            if(cost == null) {
                throw new BadRequestException(HttpStatus.BAD_REQUEST, "服务商合同未设定有效合同金额");
            }

            Optional<TCustomerContract> optionalCustomer = tCustomerContractService.findLastEffectContract(21L, order.getCustomerId(), DateUtil.parseDateToStr(new Date(), "yyyy-MM-dd"));

            if(!optionalCustomer.isPresent()) {
                throw new BadRequestException(HttpStatus.BAD_REQUEST, "客户未签订有效合同");
            }
            TCustomerContract contractCustomer = optionalCustomer.get();
            Long costCustomer = tEngineerMoneyService.getEngineerConst(contractCustomer, order.getMajor(), order.getLevel());
            if(costCustomer == null) {
                throw new BadRequestException(HttpStatus.BAD_REQUEST, "客户合同未设定有效合同金额");
            }

            order.setStatus(EnumWorkorderStatus.EVAlUATED.getValue()); //已评价,评价时间,时长等
            order.setSatisfaction(resources.getSatisfaction());
            order.setActualServiceTime(resources.getServiceTime());
            order.setContent(resources.getContent());
            order.setSuggest(resources.getSuggest());
            order.setEvaluater(resources.getEvaluator());
            order.setEvaluateTime(resources.getEvaluatorTime());
            order.setSupplierCost(cost);    //金额
            order.setCustomerCost(costCustomer); //金额
            tWorkOrderRepository.save(order);

            TWorkOrderLog workOrderLog = new TWorkOrderLog();
            workOrderLog.setContent("完成评价");
            workOrderLog.setOrderId(resources.getOrderCode());
            workOrderLog.setOrderStatus(EnumWorkorderStatus.EVAlUATED.getValue());
            workOrderLog.setOperator(resources.getInputOperator());
            workOrderLog.setCreateTime(new Timestamp(System.currentTimeMillis()));
            tWorkOrderLogService.create(workOrderLog);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchEvaluate(TCustomerSuggest resources) {
        String[] ids = resources.getRequireTool().split(","); //复用
        for(String code: ids) {
            resources.setOrderCode(code);
            this.evaluate(resources);
        }
    }
}